<?php
/**
 * ConnectBase.php 第三方用户登录注册基础类
 *
 * @author camfee <camfee@foxmail.com>
 * @date   17-8-31 下午4:26
 *
 */

namespace Passport;

use lib\mobile\Emoji;

class ConnectBase
{
    // 第三方 新浪微博
    const PLATFORM_WEIBO = 20;
    // 第三方 QQ
    const PLATFORM_QQ = 22;
    // 第三方 微信
    const PLATFORM_WEIXIN = 26;
    // 第三方 网页微信
    const PLATFORM_WEIXIN_WEB = 27;
    public static $allow_types = [
        self::PLATFORM_WEIBO => self::PLATFORM_WEIBO,
        self::PLATFORM_QQ => self::PLATFORM_QQ,
        self::PLATFORM_WEIXIN => self::PLATFORM_WEIXIN,
        self::PLATFORM_WEIXIN_WEB => self::PLATFORM_WEIXIN_WEB
    ];

    /**
     * 获取授权与openid
     *
     * @param string $code Authorization_Code or token
     * @param        $type
     * @return array|bool
     */
    public static function getOpenId($code, $type)
    {
        if (empty($code) || !in_array($type, self::$allow_types)) {
            return false;
        }
        $connect = loadconf('passport/connect');
        $return = [];
        switch ($type) {
            case self::PLATFORM_WEIBO:
                $url = 'https://api.weibo.com/2/account/get_uid.json?access_token=' . $code;
                $ret = self::curlRequest($url);
                if (!empty($ret['uid'])) {
                    $return = [
                        'AccessToken' => $code,
                        'OpenId' => $ret['uid']
                    ];
                }
                break;
            case self::PLATFORM_QQ:
                $url = 'https://graph.qq.com/oauth2.0/me?access_token=' . $code;
                $ret = self::curlRequest($url);
                if (!empty($ret['openid'])) {
                    $return = [
                        'AccessToken' => $code,
                        'OpenId' => $ret['openid']
                    ];
                }
                break;
            case self::PLATFORM_WEIXIN:
            case self::PLATFORM_WEIXIN_WEB:
                if ($type == self::PLATFORM_WEIXIN_WEB) {
                    $wx_conf = 'weixin_web';
                } else {
                    $wx_conf ='weixin';
                }
                $return = self::getWeixinOpenId($code, $connect[$wx_conf]['AppID'], $connect[$wx_conf]['AppSecret']);
                break;
            default:
                return false;
        }

        return $return;
    }

    /**
     * 由code获取微信access_token
     *
     * @param $code
     * @param $appId
     * @param $secret
     * @return array
     */
    public static function getWeixinOpenId($code, $appId, $secret)
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $data = [
            'appid' => $appId,
            'secret' => $secret,
            'code' => $code,
            'grant_type' => 'authorization_code',
        ];
        $ret = self::curlRequest($url . '?' . http_build_query($data));
        $return = [];
        if (!empty($ret['access_token'])) {
            $return = [
                'AccessToken' => $ret['access_token'],
                'RefreshToken' => $ret['refresh_token'],
                'ExpiredAt' => date('Y-m-d H:i:s', time() + $ret['expires_in']),
                'UpdatedAt' => date('Y-m-d H:i:s'),
                'OpenId' => $ret['openid']
            ];
        } else {
            debug_log('getWeixinOpenId: ' . json_encode($ret), JF_LOG_ERROR);
        }

        return $return;
    }

    /**
     * 获取用户信息
     *
     * @param $token
     * @param $openid
     * @param $type
     * @return array|bool
     */
    public static function getUserInfo($token, $openid, $type)
    {
        if (empty($token) || !in_array($type, self::$allow_types)) {
            return false;
        }
        $return = [];
        switch ($type) {
            case self::PLATFORM_WEIBO:
                $url = 'https://api.weibo.com/2/users/show.json';
                $data = [
                    'access_token' => $token,
                    'uid' => $openid,
                ];
                $ret = self::curlRequest($url . '?' . http_build_query($data));
                if (!empty($ret['id'])) {
                    $nick = mb_substr(trim(Emoji::removeEmoji($ret['screen_name'])), 0, 10);
                    $return = [
                        'NickName' => !empty($nick) ? $nick : '来自微博的用户',
                        'Avatar' => $ret['avatar_large'],
                    ];
                }
                break;
            case self::PLATFORM_QQ:
                $connect = loadconf('passport/connect');
                $url = 'https://graph.qq.com/user/get_user_info';
                $data = [
                    'access_token' => $token,
                    'openid' => $openid,
                    'oauth_consumer_key' => $connect['qq']['AppID'],
                    'format' => 'json',
                ];
                $ret = self::curlRequest($url . '?' . http_build_query($data));
                if ($ret['ret'] == 0) {
                    $nick = mb_substr(trim(Emoji::removeEmoji($ret['nickname'])), 0, 10);
                    $return = [
                        'NickName' => !empty($nick) ? $nick : '来自QQ的用户',
                        'Avatar' => $ret['figureurl_qq_2'],
                    ];
                }
                break;
            case self::PLATFORM_WEIXIN:
            case self::PLATFORM_WEIXIN_WEB:
                $url = 'https://api.weixin.qq.com/sns/userinfo';
                $data = [
                    'access_token' => $token,
                    'openid' => $openid,
                ];
                $ret = self::curlRequest($url . '?' . http_build_query($data));
                if (!empty($ret['openid'])) {
                    $nk = json_encode($ret['nickname']);
                    $nk = preg_replace("#(\\\ue[0-9a-f]{3})#i", '', $nk);
                    $nk = json_decode($nk);
                    $nick = mb_substr(trim(Emoji::removeEmoji($nk)), 0, 10);
                    $return = [
                        'NickName' => !empty($nick) ? $nick : '来自微信的用户',
                        'Avatar' => $ret['headimgurl'],
                        'UnionId' => $ret['unionid'],
                    ];
                    if (!empty($return['Avatar'])) {
                        $return['Avatar'] = preg_replace('@/[\d]+$@', '/132', $return['Avatar']);
                    }
                }
                break;
            default:
                return false;
        }

        return $return;
    }

    /**
     * 发送请求
     *
     * @param string $url     请求的地址
     * @param array  $data    需要post的数组
     * @param int    $timeout 超时时间
     * @return array       结果数组
     */
    private static function curlRequest($url, $data = [], $timeout = 10)
    {
        $time_start = microtime(true);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, true); // enable posting
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // post files
        }
        $res = curl_exec($curl);
        curl_close($curl);
        $res = preg_replace(['@^\s*callback\s*\(\s*@isU', '@\s*\)\s*;\s*$@'], '', $res);
        $res = json_decode($res, true);
        if (!empty($res) && is_string($res)) {
            parse_str($res, $res);
        }
        if (empty($res) || !is_array($res) || __ENV__ != 'ONLINE') {
            $log['url'] = $url;
            if (!empty($data)) {
                $log['post'] = $data;
            }
            $log['return'] = $res;
            $log['time'] = date('Y-m-d H:i:s');
            runtime_log('Passport/Connect/curl_request_error', $log);
        }
        $time_end = microtime(true);
        $time_out = $time_end - $time_start;
        if ($time_out > 3) {
            $log = [
                'url' => $url,
                'time_start' => $time_start,
                'time_end' => $time_end,
                'time_out' => $time_out,
                'return' => $res,
                'time' => date('Y-m-d H:i:s'),
            ];
            if (!empty($data)) {
                $log['post'] = $data;
            }
            runtime_log('Passport/Connect/curl_request_error_timeout', $log);
        }

        return $res;
    }
}